import website from '/src/config/website';
import router from '/src/router/router';

// hrefApi
const hrefApi = (url = '', type = 'new') => {
    // 新标签
    if (type == 'new') {
        //const object = router.resolve('../pages/link');
        window.open(url);
    }
    // 当前标签
    else if (type == 'now') {
        location.href = url;
    }
}

// href
export const href = (obj, type) => {
    if (!type) {
        console.log('缺少必要参数: type');
        return false;
    }
    if (!obj.url) {
        console.log('缺少必要参数: url');
        return false;
    }
    obj.type = type;
    localStorage.setItem(website.goto, JSON.stringify(obj));
    let openType = getConfig('openType');
    // 搜索
    if (type == 'search') {
        // store.dispatch('searchQuestion', {
        //     text: obj.text,
        //     id: obj.id,
        // }).then(res => {
        //     hrefApi(obj.url, openType.search.value);
        // })
    }
    // 快速访问
    else if (type == 'quick') {
        // store.dispatch('clickBookmark', {
        //     uwid: obj.id,
        //     wid: obj.wid,
        // }).then(res => {
        //     hrefApi(obj.url, openType.icon.value);
        // })
    }
    // 书签
    else if (type == 'bookmark') {
        // store.dispatch('clickBookmark', {
        //     uwid: obj.id,
        //     wid: obj.wid,
        // }).then(res => {
        //     hrefApi(obj.url, openType.bookmark.value);
        // })
    }
    // 其它
    else {
        alert('type 类型错误');
    }
};

// openPage
export const openPage = (url = '', type = '',) => {
    let openType = getConfig('openType');
    // 搜索
    if (type == 'search') {
        hrefApi(url, openType.search.value);
    }
    // 书签
    else if (type == 'bookmark') {
        hrefApi(url, openType.bookmark.value);
    }
    // 快速访问
    else if (type == 'quick') {
        hrefApi(url, openType.quick.value);
    }
}

// goUrl
export const goUrl = (url) => {
    const http = url.substr(0, 4).toLowerCase();
    const https = url.substr(0, 5).toLowerCase();
    if (http === 'http' || https === 'https') {
        location.href = url;
    } else {
        router.push(url);
    }
};

// 清理缓存
export const clearStorage = () => {
    localStorage.removeItem(website.goto);
    localStorage.removeItem(website.engine);
    localStorage.removeItem(website.engineNow);
    localStorage.removeItem(website.quick);
    localStorage.removeItem(website.bookmark);
    localStorage.removeItem(website.info);
};

// 获取(配置信息)
export const getConfig = (key) => {
    const config = localStorage.getItem(website.setting);
    if (config && JSON.parse(config)) {
        let cfg = JSON.parse(config);
        if (key) {
            return cfg[key];
        } else {
            return cfg;
        }
    }
    return '';
};

// 设置(配置信息)
export const setConfig = (key, val) => {
    let config = getConfig();
    config[key] = val;
    localStorage.setItem(website.setting, JSON.stringify(config))
}

// 获取(缓存)
export const getStorage = (key) => {
    return localStorage.getItem(key);
}

// 删除(缓存)
export const removeStorage = (key) => {
    return localStorage.removeItem(key);
}

// 设置(缓存)
export const setStorage = (key, val) => {
    return localStorage.setItem(key, val);
}

// 获取(数组缓存)
export const getArrayStorage = (key) => {
    let str = localStorage.getItem(key);
    if (str && JSON.parse(str)) {
        return JSON.parse(str);
    }
    return false;
}

// 设置(数组缓存)
export const setArrayStorage = (key, val) => {
    localStorage.setItem(key, JSON.stringify(val));
}

// 随机数
export const getRandomNum = (n = 10) => {
    let chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    let res = "";
    for (let i = 0; i < n; i++) {
        let id = Math.ceil(Math.random() * 35);
        res += chars[id];
    }
    return res;
};

// 随机数(大小数之间的)
export const getRandomInteger = (min, max) => {
    return Math.floor(Math.random() * (max - min)) + min;
};

// 判断是否chrome环境
export const isChrome = () => {
    return window.chrome && navigator.userAgent.indexOf('WebKit') > -1;
};

// 获取数组中最后一位
export const getLastValByArray = (array) => {
    return array.length > 0 ? array[array.length - 1] : '';
};

// 暗黑模式
export const openDarkMode = () => {
    let html = document.documentElement,
        themeName = 'theme',
        mode = html.getAttribute(themeName);
    html.setAttribute(themeName, (mode == 'dark-mode') ? '' : 'dark-mode');
}

// 获取Url参数
export const getQueryVariable = (variable) => {
    let query = window.location.search.substring(1);
    let vars = query.split("&");
    for (let i = 0; i < vars.length; i++) {
        let pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
    return (false);
}

// 补零
export const formatNumber = n => {
    n = n.toString();
    return n[1] ? n : '0' + n;
}

// 获取年月日
export const getFormatDateTime = (date, t) => {
    let tag = t || 'date';
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();
    let dateTime = [year, month, day].map(formatNumber).join('-');

    // 时间
    if (tag == 'time') {
        dateTime = [hour, minute, second].map(formatNumber).join(':');
    }
    // 日期时间
    else if (tag == 'datetime') {
        dateTime = dateTime + ' ' + [hour, minute, second].map(formatNumber).join(':');
    }
    // ampm
    else if (tag == 'ampm') {
        if (hour > 12) {
            dateTime = "PM";
        } else {
            dateTime = "AM";
        }
    }
    // week
    else if (tag == 'week') {
        let day = date.getDay();
        let weeks = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
        dateTime = weeks[day];
    }

    return dateTime;
}

// 浏览器扩展通信
export const sendMsgToExtension = (type = 'test', data = {msg: 'i am test msg'}, call) => {
    if (isChrome()) {
        try {
            chrome.runtime.sendMessage(
                localStorage.getItem(website.exId),
                {type: type, data: data},
                res => {
                    if (res) {
                        call(res);
                    } else {
                        console.log('小方格插件: 通信失败,请检查插件是否安装和插件ID是否匹配');
                    }
                });
        } catch (e) {
            console.log('小方格插件: chrome.runtime.sendMessage catch:', e);
        }
    } else {
        console.log('小方格插件: 只支持谷歌内核浏览器');
    }
}
